import React, { useEffect, useMemo, useState, useRef } from 'react';
import { Tabs, Input, Button, Space } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { useLocation, useNavigate } from 'react-router-dom';
import loadable from '@loadable/component';

import { getKeyFromUrl } from '@/utils';
import { SEARCH_TYPES } from '@/config';
import { SEARCH } from '@/config/url';
import useDevice, { DEVICES } from '@/hooks/useDevice';
import { getMerchList } from '@/service/api';
import styles from './index.module.scss';

const FragmentList = loadable(() => import('@/pages/Fragment/List'));

export default () => {
  const initState = () => ({
    items: [],
    loading: false,
    pageNo: 1,
    pageSize: 12,
    total: 0,

    searchType: SEARCH_TYPES[0].value,
    keyword: '',
  });
  const [state, setState] = useState(initState);
  const location = useLocation();
  const navigate = useNavigate();
  const device = useDevice();

  // 获取谷子列表
  const getList = async (options={}) => {
    const { pageNo, pageSize, searchType, keyword } = state;
    const queryData = {pageNo, pageSize, searchType, keyword, ...options};

    const st = SEARCH_TYPES.find(i => i.value === queryData.searchType);
    setState(s => ({ ...s, loading: true }));
    try {
      const [res, err] = await getMerchList({...queryData, searchType: st?.searchType||''});
      if (err) return;
      const { records, current, total, size } = res?.data || {};
      const items = (1 === current ? [] : state.items).concat(records);
      setState(s => ({
        ...s,
        items,
        pageNo: current,
        pageSize: size,
        total,
        searchType: queryData.searchType,
        keyword: queryData.keyword,
      }));
    } finally {
      setState(s => ({ ...s, loading: false }));
    }
  };

  // 加载更多
  const onLoadMore = async () => {
    getList({ pageNo: state.pageNo + 1 });
  };

  // 开始搜索
  const beginSearch = keyword => {
    getList({pageNo: 1, keyword});
  };
  // 开始搜索
  const handleClickSearch = () => {
    const word = state.keyword;
    getList({pageNo: 1, keyword: word});
  };

  // Tabs组件items
  const getTabsItem = () => {
    return SEARCH_TYPES.map(item => {
      const {value, label} = item;
      return {
        key: value,
        label,
        children: (
          <FragmentList
            type={'merch'}
            dataSource={state.items}
            showMore={state.total && state.items?.length < state.total}
            onLoadMore={onLoadMore}
            loading={state.loading}
            grid={{
              gutter: [16, 16],
              xs: 2, sm: 2, md: 3, lg: 4, xl: 4, xxl: 4
            }}
          />
        ),
      }
    })
  };

  // 切换tab开始搜索
  const handleChangeType = searchType => {
    getList({pageNo: 1, searchType});
  };

  // 首次加载
  useEffect(() => {
    const searchType = getKeyFromUrl('type') || SEARCH_TYPES[0].value;
    const keyword = getKeyFromUrl('q');
    navigate(SEARCH, { replace: true });

    setState(o => ({...o, searchType, keyword }));
    // 请求数据
    getList({ pageNo: 1, searchType, keyword });
  }, []);


  return (
    <div className={styles['container']}>
      <div className={styles['search-container']} style={{width: device === DEVICES.MOBILE ? '90%' : '80%'}}>
        <div className={styles['input-container']}>
          <Input.Search
              value={state.keyword}
              onChange={e => setState(s => ({ ...s, keyword: e.target.value }))}
              onSearch={beginSearch}
              style={{width: '100%'}}
              placeholder='输入关键词搜索'
          />
          <Button onClick={handleClickSearch} className={styles['search-btn']} shape="circle" type="text" icon={<SearchOutlined/>}></Button>
        </div>
      </div>
      <div className={styles['tabs-container']}>
        <Tabs
          items={getTabsItem()}
          activeKey={state.searchType}
          onChange={handleChangeType}
          type="border-card"
          destroyOnHidden={true}
        />
      </div>
    </div>
  );
}
